import store from '../store/index'
import SDK from '../libs/sdk/connection'
import config from './WebIMConfig'
export const WebIM = SDK;
WebIM.config = config
WebIM.conn = new WebIM.connection({
    isMultiLoginSessions: WebIM.config.isMultiLoginSessions, //是否可以登录多个网页，并在所有网页上接收消息
    https: WebIM.config.https, //是否使用HTTPS 
    url: WebIM.config.xmppURL, //XMPP server
    apiUrl: WebIM.config.apiUrl,
    isAutoLogin: WebIM.config.isAutoLogin, //自动登录
    heartBeatWait: 4500, //心跳间隔
    autoReconnectNumMax: WebIM.config.autoReconnectNumMax, //自动重连次数
    autoReconnectInterval: WebIM.config.autoReconnectInterval, //每个重新连接之间的间隔秒, 自动重连次数大于1时有效。
});
// 注册
export const register = () => {
	const userInfo = uni.getStorageSync('USER_INFO')
	if (!userInfo) {
			return
	}
	let options = {
			username: JSON.parse(userInfo).userId,
			password: '123456',
			nickname: JSON.parse(userInfo).userName,
			appKey: WebIM.config.appkey,
			success: function() {
					loginIm()
			},
			error: function() {
					loginIm()
			},
			apiUrl: WebIM.config.apiURL
	}
	WebIM.utils.registerUser(options);
}
    // 登录
export const loginIm = () => {
	uni.showLoading({
		title: '聊天连接中'
	})
	const userInfo = uni.getStorageSync('USER_INFO')
	let options = {
			apiUrl: WebIM.config.apiURL,
			user: JSON.parse(userInfo).userId,
			pwd: '123456',
			appKey: WebIM.config.appkey
	};
	WebIM.conn.open(options)
	uni.hideLoading()
	initIm()
}
export function initIm() {
	WebIM.conn.listen({
			onOpened: function(message) { //连接成功回调
					console.log('打开连接')
			},
			onClosed: function(message) {
					console.log('关闭连接')
			},
			onTextMessage: function ( message ) {
					chatRecord(message.from, message, 'text').receiveMessages()
			},    //收到文本消息
			onPictureMessage: function ( message ) {
					chatRecord(message.from, message, 'img').receiveMessages()
			}, //收到图片消息
			onAudioMessage: function ( message ) {
					chatRecord(message.from, message, 'audio').receiveMessages()
			},   //收到音频消息
			onError: function(message) {
				console.log(message)
				// register()
			}, //失败回调
	})
}

class ChatRecord {
	constructor(targetId,message,type) {
		this.targetId = targetId
		this.message = message
		this.type = type
		this.path = 'pages/chat/index'
		this.recordLength = 16 //页面展示数据条数
  }
	// 存储消息
	async getChat(info) {
		const messageList = store.getters.messageList
		const messageInfo = { // 消息列表
			...info
		}
		const chat = uni.getStorageSync('CHAT')
		const {userId} = JSON.parse(uni.getStorageSync('USER_INFO'))
		if (chat) {
			console.log(this.targetId)
			if (chat[this.targetId]) {
				chat[this.targetId].msgContent.push(info)
				uni.setStorageSync('CHAT',chat)
				const index = messageList.findIndex((item) => {
					if (userId === item.fromId) {
						console.log(item.targetId, this.targetId)
						return item.targetId === this.targetId
					} else {
						return item.fromId === this.targetId
					}
					
				})
				console.log(index)
				messageList[index] = messageInfo
				messageList.sort((a, b) => b.time - a.time)
				store.dispatch('chat/updateMessage',messageList)
			} else {
				chat[this.targetId] = {
					msgContent: [
						info
					]
				},
				uni.setStorageSync('CHAT',chat)
				messageList.unshift(messageInfo)
				store.dispatch('chat/updateMessage',messageList)
			}
		} else {
			const createdChat = {}
			createdChat[this.targetId] = {
				msgContent: [
					info
				]
			}
			uni.setStorageSync('CHAT',createdChat)
			messageList.push(messageInfo)
			store.dispatch('chat/updateMessage',messageList)
		}
	}
	// 处理消息
	receiveMessages() {
		this.disposeType()
	}
	// 处理当前页面数据
	currentChat() {
		const chat = uni.getStorageSync('CHAT')
		const route = getCurrentPages().pop().is
		if (route === this.path) {
			if (this.targetId === store.getters.chatTarget) {
				const history = store.getters.history
				const content = chat[this.targetId].msgContent[chat[this.targetId].msgContent.length-1]
				history.push(content)
				store.dispatch('chat/updateHistory',history)
			}
		} else {
			return
		}
	}
	// 从其他页面进入消息展示
	messageShow() {
		const chat = uni.getStorageSync('CHAT')
		if (!chat[this.targetId]) {
			store.dispatch('chat/updateHistory',[])
		} else {
			const chatLength = chat[this.targetId].msgContent.length
			console.log(chatLength)
			if ( chatLength > this.recordLength) {
				store.dispatch('chat/updateHistory',chat[this.targetId].msgContent.slice(-16))
			} else {
				store.dispatch('chat/updateHistory',chat[this.targetId].msgContent)
			}
		}
	}
	// 历史数据展示
	historyRecordShow(page) {
		const chat = uni.getStorageSync('CHAT')
		const chatLength = chat[this.targetId].msgContent.length
		const recordLength = store.getters.history.length
		console.log(chatLength,recordLength)
		if (chatLength > recordLength) {
			uni.showLoading({
				title: '历史记录加载中'
			})
			const size = page * this.recordLength
			store.dispatch('chat/updateHistory',chat[this.targetId].msgContent.slice(-size))
			setTimeout(()=>{
				uni.hideLoading()
			},1000)
			return true
		} else {
			return false
		}
	}
	// 处理已读
	alreadyRead() {
		const messageList = store.getters.messageList
		const chat = uni.getStorageSync('CHAT')
		console.log(store.getters.chatTarget, this.targetId)
		if (this.targetId === store.getters.chatTarget) {
			if (chat[this.targetId]) {
				const newChat = chat[this.targetId].msgContent.map((item) => {
					item.unread = false
					return item
				})
				chat[this.targetId].msgContent = newChat
				// 可以修改已读时间
				const index = messageList.findIndex((item) => {
					return item.targetId = this.targetId
				})
				messageList[index].unread = false
				messageList.sort((a,b) => b.time-a.time)
				uni.setStorageSync('CHAT',chat)
				store.dispatch('chat/updateMessage',messageList)
			}
		}
	}
	// 处理消息类型
	async disposeType() {
		const types = ['text', 'img','audio']
		switch (this.type){
			case types[0]:
			console.log('text')
				await this.messageText()
				break;
			case types[1]:
				await this.messageImage()
				break;
			default:
				await this.messageAudio()
				break;
		}
	}
	messageText() {
		let info
		const {id,ext, data} = this.message
		const length = Object.keys(ext).length
		if (!length) {
			info = {
				fromId: ext.fromId || id, //来自谁的信息
				userPhoto: '',
				nickName: '',
				time: +new Date(),
				unread: true,
				type: this.type,
				content: data,
				targetName: '',
				targetPhoto: '',
				targetId: this.message.to
			}
		} else {
			info = {
				fromId: ext.fromId || id, //来自谁的信息
				userPhoto: ext.avatar,
				nickName: ext.nickName,
				time: ext.time,
				unread: ext.unread,
				type: ext.type,
				content: data,
				targetName: ext.targetName,
				targetPhoto: ext.targetPhoto,
				targetId: this.message.to
			}
		}
		console.log(info)
		this.getChat(info)
		this.currentChat()
	}
	messageImage() {
		const {userId} = JSON.parse(uni.getStorageSync('USER_INFO'))
		const _this = this
		let info
		const {id,ext,url,width,height} = this.message
		const length = Object.keys(ext).length
		if (!length) {
			info = {
				fromId: ext.fromId || id  , //来自谁的信息
				userPhoto: '',
				nickName: '',
				time: +new Date(),
				unread: true,
				type: this.type,
				targetName: '',
				targetPhoto: '',
				targetId: this.message.to
			}
		} else {
			info = {
				fromId: ext.fromId || id, //来自谁的信息
				userPhoto: ext.avatar,
				nickName: ext.nickName,
				time: ext.time,
				unread: ext.unread,
				type: ext.type,
				width: uni.upx2px(width),
				height: uni.upx2px(height),
				targetName: ext.targetName,
				targetPhoto: ext.targetPhoto,
				targetId: this.message.to
			}
		}
		console.log(this.message)
		if (userId !== this.message.ext.fromId) {
			uni.downloadFile({
				url: url, //仅为示例，并非真实的资源
				success: (res) => {
					if (res.statusCode === 200) {
						uni.saveFile({
							tempFilePath: res.tempFilePath,
							success: function (e) {
								const savedFilePath = e.savedFilePath;
								info.path = savedFilePath
								info.url = url //下载路径
								console.log(info)
								_this.getChat(info)
								_this.currentChat()
							}
						});
					}
				}
			});
		} else {
			uni.saveFile({
				tempFilePath: ext.path,
				success: function (e) {
					const savedFilePath = e.savedFilePath;
					info.path = savedFilePath
					info.url = url //下载路径
					_this.getChat(info)
					_this.currentChat()
				}
			});
		}
		
	}
	messageAudio() {
		const {userId} = JSON.parse(uni.getStorageSync('USER_INFO'))
		const _this = this
		let info
		const {id,ext,url} = this.message
		const length = Object.keys(ext).length
		if (!length) {
			info = {
				fromId: ext.fromId || id, //来自谁的信息
				userPhoto: '',
				nickName: '',
				time: +new Date(),
				unread: true,
				type: this.type,
				targetName: '',
				targetPhoto: '',
				targetId: this.message.to
			}
		} else {
			info = {
				fromId: ext.fromId || id, //来自谁的信息
				userPhoto: ext.avatar,
				nickName: ext.nickName,
				time: ext.time,
				unread: ext.unread,
				type: ext.type,
				targetName: ext.targetName,
				targetPhoto: ext.targetPhoto,
				targetId: this.message.to
			}
		}
		if (userId !== this.message.ext.fromId) {
			uni.downloadFile({
				url: url, //仅为示例，并非真实的资源
				success: (res) => {
					if (res.statusCode === 200) {
						uni.saveFile({
							tempFilePath: res.tempFilePath,
							success: function (e) {
								const savedFilePath = e.savedFilePath;
								info.path = savedFilePath
								info.url = url //下载路径
								_this.getChat(info)
								_this.currentChat()
							}
						});
					}
				}
			});
		} else {
			uni.saveFile({
				tempFilePath: ext.path,
				success: function (e) {
					const savedFilePath = e.savedFilePath;
					info.path = savedFilePath
					info.url = url //下载路径
					_this.getChat(info)
					_this.currentChat()
				}
			});
		}
	}
}

export const chatRecord  = (targetId,message = {},type='text') => {
	return new ChatRecord(targetId,message,type)
}
